<!-- src/views/Item/Item.vue -->
<template>
  <div class="item-list">
    <el-table :data="items" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="名称"></el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>
      <el-table-column prop="price" label="价格"></el-table-column>
      <el-table-column prop="stock" label="库存"></el-table-column>
      <el-table-column prop="status" label="状态"></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button @click="editItem(scope.row)">编辑</el-button>
          <el-button type="danger" @click="deleteItem(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-page="currentPage"
        @current-change="handlePageChange"
    ></el-pagination>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { itemApi } from '@/api/itemApi.js';

const items = ref([]);
const total = ref(0);
const currentPage = ref(1);

const fetchItems = async (page = 1) => {
  try {
    const response = await itemApi.queryItemByPage(page, 10);
    items.value = response.data.records;
    total.value = response.data.total;
    currentPage.value = page;
  } catch (error) {
    console.error('Failed to fetch items:', error);
    ElMessage.error('加载商品失败');
  }
};

onMounted(() => {
  fetchItems();
});

const handlePageChange = (newPage) => {
  fetchItems(newPage);
};

const editItem = (item) => {
  // 跳转到编辑页面或弹出编辑对话框
  console.log('Edit item:', item);
};

const deleteItem = async (id) => {
  try {
    await itemApi.deleteItem(id);
    ElMessage.success('删除成功');
    fetchItems(currentPage.value);
  } catch (error) {
    console.error('Failed to delete item:', error);
    ElMessage.error('删除失败');
  }
};
</script>

<style scoped>
.item-list {
  padding: 20px;
}
</style>
